package paper.web.controller.topic;

import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import keter.web.util.MediaTypes;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import paper.dao.CommentsDao;
import paper.domain.Comments;
import paper.domain.Topic;
import paper.service.TopicService;
import paper.web.controller.BaseController;

@Controller
@PreAuthorize("hasRole('TEACHER')")
@RequestMapping("/paper/topic/confirm")
public class TopicConfirmController extends BaseController {
	
	@Autowired
	TopicService service;
	
	@Autowired
	CommentsDao cdao;
	
	Long topicId;
	/**
	 * Logger for this class
	 */
	private static final Logger logger = LoggerFactory.getLogger(TopicConfirmController.class);
	
	public static class Views {
		private static final String Prefix = "paper/topic/confirm";
		static final String Index = to_(Prefix) + "index";
		static final String Add = to_(Prefix) + "add";
	}
	
	/**
	 * <p>Method ：login
	 * <p>Description : 处理控制台请求
	 * @return 
	 * @author  gulixing@msn.com
	 * @version 1.0.0
	 */
	@RequestMapping(value = Routes.Index, method = RequestMethod.GET)
	public String index(Model model) {
		return Views.Index;
	}
	
	@RequestMapping(value = "/add/{topicId}", method = RequestMethod.GET)
	public String add(@PathVariable Long topicId, Model model) {	
		this.topicId = topicId;
		return Views.Add;
	}
	
	@RequestMapping(value = "/add/result/{result}", method = RequestMethod.POST, consumes = MediaTypes.JSON)
	@ResponseBody
	public Map<String, String> add(@RequestBody Comments comments,@PathVariable String result, HttpServletResponse response) throws UnsupportedEncodingException {
    	Map<String, String> ajaxMap = getAjaxMap();
    	comments.setMainId(topicId);
    	comments.setCreatorId(getCurrentUser().getId());
    	cdao.save(comments);     	
    	Topic t= service.getTopicDao().findOne(topicId);
    	t.setStatus(result);
    	service.confirm(t);    	
		return ajaxMap;
	}
	
	@RequestMapping(value = "/getTopic", method = RequestMethod.GET)
	@ResponseBody
	public List<Topic> getTopic() throws Exception {
		return service.getTopicDao().findSubmitOrPassByMaster(getCurrentUser().getId());
	}
}